<?php
class App{
	static function start(){
		App::init();
		//用户认证
		AuthHelper::auth();
		App::exec();
	}
	static function init(){
		$pass = true;
		//如果参数未设置或者为空则用默认index替代
		$app = isset($_GET['app']) && (!empty($_GET['app'])) ? $_GET['app'] : 'index';
		$controller = isset($_GET['c']) && (!empty($_GET['c'])) ? $_GET['c'] : 'index';
		$action = isset($_GET['a']) && (!empty($_GET['a'])) ? $_GET['a'] : 'index';
		//检查参数是否合法(只能包含数字和字母)
		foreach (array($app, $controller, $action) as $v) {
			if(!preg_match("/^[0-9a-zA-Z]+$/", $v)){
				$pass = false;
			}
		}
		if((!$pass) || (!is_dir(APP_PATH.DS.$app))){
			//不合法跳转到404
			RouteHelper::jump(U('404'));
		}
		//绑定应用控制器和方法
		define('B_APP', $app);
		define('B_APP_PATH', APP_PATH.DS.$app);
		define('B_CONTROLLER', ucfirst($controller));
		define('B_ACTION', $action);
		//加载应用配置
		if(is_file(B_APP_PATH.DS.'conf'.DS.ENV.'.config.php')){
			C('APP', include(B_APP_PATH.DS.'conf'.DS.ENV.'.config.php'));
		}
		//加载应用环境
		if(is_dir(B_APP_PATH.DS.'include')){
			//有公共function则加载
			if(is_file(B_APP_PATH.DS.'include'.DS.'function.php'))
				include B_APP_PATH.DS.'include'.DS.'function.php';
			//加载到动态classpath中
			dynamic_load(B_APP_PATH.DS.'include', true);
		}
		//如果自定义了model则加载到classpath中
		if(is_dir(B_APP_PATH.DS.'model')){
			dynamic_load(B_APP_PATH.DS.'model',true);
		}
	}
	static function exec(){
		//处理应用
		//控制器检查
		if(!is_file(B_APP_PATH.DS.'controller'.DS.strtolower(B_CONTROLLER).'.php'))
			RouteHelper::jump(U('404'));
		//控制器存在 引入
		include B_APP_PATH.DS.'controller'.DS.strtolower(B_CONTROLLER).'.php';
		//反射控制器类
		$controller_class = new ReflectionClass(B_CONTROLLER.'Controller');
		//检查方法
		if(!$controller_class->hasMethod(B_ACTION)){
			RouteHelper::jump(U('404'));
		}
		$controller = $controller_class->newInstance();
		$preauth = $controller_class->getMethod('preauth');
		//验证访问权限
		if(!$preauth->invoke($controller)){
			RouteHelper::jump(U('404'));
		}
		$action= $controller_class->getMethod(B_ACTION);
		$action->invoke($controller);
	}
}